<template>
  <div class="activity-type-select">
      <d-checkbox 
        value="all" 
        :checked="isAllSelected"
        :half-checked="halfCheck"
        @change="toggleAllTypes"
      >
        <span class="type-label">全部</span>
      </d-checkbox>
    <CheckboxGroup v-model="selectedTypes" @change="handleChange" direction="row" class="activity-type-select__checkbox-group">
      <d-checkbox 
        v-for="type in types" 
        :key="type"
        :value="type"
      >
        <div class="type-content">
          <span class="type-dot" :style="{ backgroundColor: LIVE_BROADCAST_COLOR[type][0] }"></span>
          <span class="type-label">{{ type }}</span>
        </div>
      </d-checkbox>
    </CheckboxGroup>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, defineProps, defineEmits } from 'vue';
import { CheckboxGroup } from 'vue-devui/checkbox';
import { LIVE_BROADCAST_COLOR } from '@/constant';

const props = defineProps({
  modelValue: {
    type: Array as () => string[],
    default: () => []
  },
  types: {
    type: Array,
    default: () => []
  }
});

const emit = defineEmits(['update:modelValue', 'change']);

// 所有可选类型的值列表
const allTypeValues = computed(() => {
  return props.types || [];
});

// 选中的类型
const selectedTypes = ref<string[]>([...props.modelValue]);

// 是否全选
const isAllSelected = computed(() => {
  return (selectedTypes.value.length === allTypeValues.value.length && allTypeValues.value.every(value => selectedTypes.value.includes(value)));
});

// 是否半选状态（部分选中）
const halfCheck = computed(() => {
  return !isAllSelected.value && selectedTypes.value.length > 0 && selectedTypes.value.some(value => allTypeValues.value.includes(value));
});

// 监听外部传入的值变化
watch(() => props.modelValue, (newVal) => {
  selectedTypes.value = [...newVal];
}, { deep: true });

// 处理选择变化
const handleChange = (values: string[]) => {
  emit('change', values);
};

// 切换全选状态
const toggleAllTypes = (checked: boolean) => {
  if (checked) {
    selectedTypes.value = [...allTypeValues.value];
  } else {
    selectedTypes.value = [];
  }
  emit('change', selectedTypes.value);
};
</script>

<style lang="scss" scoped>
.activity-type-select {
  display: flex;
  align-items: center;
  &__checkbox-group {
    margin-left: 12px;
  }
  .type-label {
    white-space: nowrap;
  }
  .type-content {
    display: flex;
    align-items: center;
    gap: 8px;
    
    .type-dot {
      width: 6px;
      height: 6px;
      border-radius: 50%;
    }
  }
  :deep(.devui-checkbox__group>*) {
    margin-top: 0;
    margin-right: 12px;
  }
  :deep(.devui-checkbox__group.is-row div:not(:last-child)) {
    margin-right: 12px;
  }
}
</style>